package com.erji.common.mybatis.type;


import com.alibaba.fastjson2.JSON;
import com.erji.common.cos.domain.FileObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@MappedJdbcTypes({JdbcType.VARCHAR})
@MappedTypes({FileObject[].class})
public class FileObjectArrayTypeHandler extends BaseTypeHandler<FileObject[]> {
    public FileObjectArrayTypeHandler() {
    }

    public void setNonNullParameter(PreparedStatement preparedStatement, int i, FileObject[] parameter, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, JSON.toJSONString(parameter));
    }

    public FileObject[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return this.convertToFileObjectArray(rs.getString(columnName));
    }

    public FileObject[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return this.convertToFileObjectArray(rs.getString(columnIndex));
    }

    public FileObject[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return this.convertToFileObjectArray(cs.getString(columnIndex));
    }

    private FileObject[] convertToFileObjectArray(String res) {
        if (StringUtils.isBlank(res)) {
            return new FileObject[0];
        }

        List<FileObject> fileObjects = new ArrayList<>();
        try {
            fileObjects = JSON.parseArray(res, FileObject.class);
        } catch (Exception e) {

        }
        return fileObjects.toArray(new FileObject[0]);
    }
}
